/**
 * https://leetcode-cn.com/problems/walking-robot-simulation/submissions/
 * @param {number[]} commands
 * @param {number[][]} obstacles
 * @return {number}
 */
 var robotSim = function(commands, obstacles) {
  const obstacleSet = new Set(obstacles.map(([x, y]) => `${x},${y}`));
  const current = [0, 0];
  let maxDistance = 0;
  // 方向数组 E S W N
  const directionX = [1, 0, -1, 0];
  const directionY = [0, -1, 0, 1];
  let direction = 3; // init direction North
  function step(command, i) {
      if (command === -2) {
          direction = (direction + 3) % 4
      } else if (command === -1) {
          direction = (direction + 1) % 4
      } else if (command >= 1 && command <= 9){
          for (let i = 0; i < command; i++) {
              const nextPos = `${current[0] + directionX[direction]},${current[1] + directionY[direction]}`;
              if (obstacleSet.has(nextPos)) {
                  break;
              }
              current[0] += directionX[direction];
              current[1] += directionY[direction];
              maxDistance = Math.max(maxDistance, Math.pow(current[0], 2) + Math.pow(current[1], 2));
          }
      }
  }
  commands.forEach(step);
  return maxDistance;
};
